<?php

class Social_Controller_Browse_Google_Oauth2callback
{

	function execute($request)
	{

		$adapter = Nuo::getObject('social/adapter/google');
		$clientApi = $adapter -> getClientApi();

		$accessToken = NULL;

		//$client->setDeveloperKey('insert_your_developer_key');

		if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'access_denied')
		{
			echo 'error occur!';
			exit();
		}

		if (isset($_GET['code']))
		{
			$clientApi -> authenticate();
			$accessToken = $clientApi -> getAccessToken();
		}

		if ($accessToken)
		{
			$req = new apiHttpRequest("https://www.googleapis.com/oauth2/v1/userinfo?alt=json");

			$val = $clientApi -> getIo() -> authenticatedRequest($req);

			// The contacts api only returns XML responses.
			$profile = json_decode($val -> getResponseBody(), true);
			
			/**
			 * prepare connected data
			 */
			$data = array(
				'uid' => $profile['id'],
				'name' => $profile['name'],
				'token' => $accessToken,
				'link' => $profile['link'],
				'photo' => $profile['picture'],
				'email' => $profile['email'],
			);

			Nuo::getApi('social') -> addConnect($adapter -> getServiceId(), $data);
		}
		else
		{
			$authUrl = $clientApi -> createAuthUrl();
		}

		if (isset($authUrl))
		{
			Nuo::redirect($authUrl);
			echo $authUrl;
			exit ;
		}
		else
		{
			print "<a class=logout href='?logout'>Logout</a>";
		}
	}

}
